const http = require("http");
const fs = require("fs");
const path = require("path");
var imgPath = path.join(__dirname, "./icon.png");
var dirPath = path.join(__dirname, "./fileDir");

function judge(a) {
    if (a < 10) {
        return "0" + a;
    } else {
        return a;
    }
}

function format(t) {
    var d = new Date(t);
    var y = d.getFullYear();
    var m = d.getMonth() + 1;
    var s = d.getDate();
    return y + "-" + judge(m) + "-" + judge(s);
}

http.createServer((req, res) => {
    var jUrlStr = req.url;
    /**当请求的资源路径是/时,相应网页文件到浏览器 */
    var filePath = path.join(__dirname, "./index.html");
    if (jUrlStr == "/") {
        var fileContent = fs.readFileSync(filePath);
        res.writeHead(200, { "Content-Type": "text/html;charset=utf-8" });
        res.write(fileContent);
        res.end();
    } else if (jUrlStr == "/icon.png") {
        var imgContent = fs.readFileSync(imgPath);
        res.writeHead(200, { "Content-Type": "image/png;charset=utf-8" });
        res.write(imgContent);
        res.end();
    } else if (jUrlStr == "/getlist") {
        var arr = [];
        var dir = fs.readdirSync(dirPath);
        for (var i = 0; i < dir.length; i++) {
            var obj = {};
            var file = path.join(dirPath, dir[i]);
            var stat = fs.statSync(file);
            if (stat.isDirectory()) {
                obj.fileType = "folder";
            } else if (stat.isFile()) {
                obj.fileType = "file";
            }
            obj.fileName = dir[i].split(".")[0] || "";
            obj.fileSize = stat.size;
            obj.fileTime = format(stat.birthtime);
            arr.push(obj);
        }
        var jsonString = JSON.stringify(arr);
        res.writeHead(200, { "Content-Type": "text/plain;charset=utf-8" });
        res.write(jsonString);
        res.end();
    }
}).listen(8081);
console.log("server is listening on 8081");
